<!doctype html>
<html lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=11,IE=10,IE=9,IE=8">
    <meta name="baidu-site-verification" content="dIcXMeY8Ya">
    
    <title>Lucene快速入门知识和案例 | 墨染红尘</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
    <meta name="keywords" content="三更编程, JAVA, 算法, 后端开发">
    <meta name="description" content="菜豆个人博客">

    
    <link rel="alternative" href="/atom.xml" title="墨染红尘" type="application/atom+xml">
    
    
    <link rel="shortcut icon" href="/blog/logo.png">
    
    <link rel="stylesheet" href="/blog/css/style.css">
    <!--[if lt IE 9]>
    <script src="/blog/js/html5.js"></script>
    <![endif]-->
    
<script>
    var _hmt = _hmt || [];
    (function() {
        var hm = document.createElement("script");
        hm.src = "//hm.baidu.com/hm.js?fd459238242776d173cdc64918fb32f2";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>


</head>
</html>
<body class="home">
    <!--[if lt IE 9]>
    <div class="browsehappy">
        当前网页 <strong>不支持</strong>
        你正在使用的浏览器. 为了正常的访问, 请 <a href="http://browsehappy.com/">升级你的浏览器</a>.
    </div>
    <![endif]-->

    <!-- 博客头部 -->
    <header class="header">
    <section class="container header-main">
        <div class="logo">
            <a href="/blog/">
                <div class="cover">
                    <span class="name">墨染红尘</span>
                    <span class="description">堇色流年·追梦少年</span>
                </div>
            </a>
        </div>
        <div class="dropnav icon-paragraph-justify" id="JELON__btnDropNav"></div>
        <ul class="menu hidden" id="JELON__menu">
            
            <li rel="/blog/2019/05/15/Lucene/2019-05-12-Lucene快速入门案例/index.html" class="item ">
                <a href="/blog/" title="首页" class="icon-home">&nbsp;首页</a>
            </li>
            
        </ul>
        <div class="profile clearfix">
            <div class="feeds fl">
                
                
                <p class="links">
                    
                        <a href="https://github.com/fxiaoyu97" target="_blank">Github</a>
                        |
                    
                        <a href target="_blank">Hosted by Coding Pages</a>
                        
                    
                </p>
                <p class="sns">
                    
                    <a href="javascript: void(0);" class="wechat">
                        <b>■</b>
                        公众号
                        <span class="popover">
                            <img src="/blog/img/wechat_mp.jpg" width="120" height="120" alt="我的微信订阅号">
                            <i class="arrow"></i>
                        </span>
                    </a>
                </p>
                
            </div>
            <div class="avatar fr">
                <img src="/blog/img/avatar.jpg" alt="avatar" title="Jelon">
            </div>
        </div>
    </section>
</header>


    <!-- 博客正文 -->
    <div class="container body clearfix">
        <section class="content">
            <div class="content-main widget">
                <!-- 文章页 -->
<!-- 文章 -->
<article class="post article">
    <header class="text-center">
        <h3 class="post-title"><span>Lucene快速入门知识和案例</span></h3>
    </header>
    <p class="post-meta text-center">
        Calos 发表于
        <time datetime="2019-05-14T16:00:00.000Z">2019-05-15</time>
    </p>
    <div class="post-content">
        <p>Lucene快速入门案例，学习黑马Lucene教程以后的笔记，添加一些自己的学习心得。</p>
<hr>
<h2 id="1、流程分析"><a href="#1、流程分析" class="headerlink" title="1、流程分析"></a><font color="#CD6839">1、流程分析</font></h2><p><img src="\blog\img\thumbnail\13.png" alt></p>
<p>1、绿色表示索引过程，对要搜索的原始内容进行索引构建一个索引库，索引过程包括：确定原始内容即要搜索的内容 —&gt; 采集文档 —&gt; 创建文档 —&gt; 分析文档 —&gt; 索引文档。</p>
<p>2、红色表示搜索过程，从索引库中搜索内容，搜索过程包括：用户通过搜索界面 —&gt; 创建查询 —&gt; 执行搜索，从索引库搜索 —&gt; 渲染搜索结果</p>
<h2 id="2、生成索引看库"><a href="#2、生成索引看库" class="headerlink" title="2、生成索引看库"></a><font color="#CD6839">2、生成索引看库</font></h2><h3 id="2-1、获得原始文档"><a href="#2-1、获得原始文档" class="headerlink" title="2.1、获得原始文档"></a><font color="#FF8247">2.1、获得原始文档</font></h3><p>​        原始文档，简单地说就是我们准备搜索的内容。可以是互联网上的网页、数据库中的数据、磁盘上的文件等。 </p>
<h3 id="2-2、创建文档对象"><a href="#2-2、创建文档对象" class="headerlink" title="2.2、创建文档对象"></a><font color="#FF8247">2.2、创建文档对象</font></h3><p>​        在创建索引前，我们需要将原始内容创建成文档（Document），一个文档中会包括很多的的域（Field），然后在域中存储原始文档的一些内容。<br>​        每一个文件可以当成一个document，Document下面可以包含多个Field(域)，域由两部分组成：域的名称和值，可以理解为以<strong><em>key和value</em></strong>的形式存放数据。其实还有一个类型，用来表示域中存放数据的类型，这个不用我们考虑，可以在调用方法时作区分。比如我们现在以磁盘上面的文件为例，那么每个文件下可以包含四个域：name（名称）、path（路径）、context（内容）、size（文件大小）。如下所示：</p>
<table>
<thead>
<tr>
<th>名称</th>
<th>值</th>
</tr>
</thead>
<tbody>
<tr>
<td>name</td>
<td>Helloworld.java</td>
</tr>
<tr>
<td>path</td>
<td>f://Helloworld.java</td>
</tr>
<tr>
<td>context</td>
<td>public class HelloWorld…</td>
</tr>
<tr>
<td>size</td>
<td>4562</td>
</tr>
</tbody>
</table>
<p>​        <strong>注意：每个文档都有一个唯一的编号，就是文档id。</strong></p>
<p>Field域还有三个属性，如下所示：</p>
<ul>
<li><strong>是否分析：</strong>是否对域的内容进行分词处理。前提是我们要对域的内容进行查询。</li>
<li><strong>是否索引：</strong>将Field分析后的词或整个Field值进行索引，只有索引的内容才能搜索到。比如：商品名称、商品简介分析后进行索引，订单号、身份证号不用分析但也要索引，这些将来都要作为查询条件。</li>
<li><strong>是否存储：</strong>将Field值存储在文档中，存储在文档中的Field才可以从Document中获取比如：商品名称、订单号，凡是将来要从Document中获取的Field都要存储。</li>
</ul>
<p>总结下来就是，是否查询这些内容决定了是否进行分析，时候进行搜索决定了是否索引，是否眼展示内容决定了是否进行存储。</p>
<p>附上一张表，用来展示各个方法对这三个属性的条件。</p>
<table>
<thead>
<tr>
<th>Field类</th>
<th>数据类型</th>
<th>Analyzed分析</th>
<th>Indexed索引</th>
<th>Stored存储</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><font size="2">StringField(FieldName, FieldValue,Store.YES))</font></td>
<td>字符串</td>
<td>N</td>
<td>Y</td>
<td>Y或N</td>
<td style="text-align:left">这个Field用来构建一个字符串Field，但是不会进行分析，会将整个串存储在索引中，比如(订单号,姓名等)是否存储在文档中用Store.YES或Store.NO决定</td>
</tr>
<tr>
<td><font size="2">LongPoint(String name, long point)</font></td>
<td>Long型</td>
<td>Y</td>
<td>Y</td>
<td>N</td>
<td style="text-align:left">可以使用LongPoint、IntPoint等类型存储数值类型的数据。让数值类型可以进行索引。但是不能存储数据，如果想存储数据还需要使用StoredField。</td>
</tr>
<tr>
<td><font size="2">StoredField(FieldName, FieldValue) </font></td>
<td>重载方法，支持多种类型</td>
<td>N</td>
<td>N</td>
<td>Y</td>
<td style="text-align:left">这个Field用来构建不同类型Field不分析，不索引，但要Field存储在文档中</td>
</tr>
<tr>
<td><font size="2">TextField(FieldName, FieldValue, Store.NO)或TextField(FieldName, reader)</font></td>
<td>字符串或流</td>
<td>Y</td>
<td>Y</td>
<td>Y或N</td>
<td style="text-align:left">如果是一个Reader, lucene猜测内容比较多,会采用Unstored的策略.</td>
</tr>
</tbody>
</table>
<hr>
<h3 id="2-3、分析文档"><a href="#2-3、分析文档" class="headerlink" title="2.3、分析文档"></a><font color="#FF8247">2.3、分析文档</font></h3><p>​        说白了这就是一个分词的操作，就是挑选出关键词，去除没用的。比如根据空格进行字符串的拆分得到关键词列表、将关键词中的字母转为小写、去除标点符号、去除停用词（即需要过滤掉的词汇）等。</p>
<p><strong>原文档内容：</strong></p>
<font color="#483D8B">Lucene is a Java full-text search engine.  Lucene is not a complete<br>application, but rather a code library and API that can easily be used<br>to add search capabilities to applications. </font>

<p><strong>分析后得到的语汇单元：</strong></p>
<font color="#483D8B">lucene、java、full、search、engine。。。。</font>

<p>​        分析得到的每个关键词封装成一个Term对象，Term中包含两部分：一部分是关键词所在的域名，另一部分是关键词的内容。不同的域中拆分出来的相同的关键词是不同的term。 </p>
<h3 id="2-4、创建索引"><a href="#2-4、创建索引" class="headerlink" title="2.4、创建索引"></a><font color="#FF8247">2.4、创建索引</font></h3><p>​            说了那么多，我们先进行导包操作，需要导入下面这些包，按照从左往右的顺序依次为：文件输入输出、汉语词法分析、Lucene包。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">commons-io、IK-Analyzer-1.0-SNAPSHOT、lucene-analyzers-common-7.4.0、lucene-core-7.4.0、lucene-queryparser-7.4.0</span><br></pre></td></tr></table></figure>
<p>接着来看一下创建索引的方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">createIndex</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">//1、创建一个Director对象，指定索引库保存的位置。</span></span><br><span class="line">        <span class="comment">//把索引库保存在内存中</span></span><br><span class="line">        <span class="comment">//Directory directory = new RAMDirectory();</span></span><br><span class="line">        <span class="comment">//把索引库保存在磁盘</span></span><br><span class="line">        Directory directory = FSDirectory.open(<span class="keyword">new</span> File(<span class="string">"F:\\index"</span>).toPath());</span><br><span class="line">        <span class="comment">//2、基于Directory对象创建一个IndexWriter对象</span></span><br><span class="line">        IndexWriterConfig config = <span class="keyword">new</span> IndexWriterConfig(<span class="keyword">new</span> IKAnalyzer());</span><br><span class="line">        IndexWriter indexWriter = <span class="keyword">new</span> IndexWriter(directory, config);</span><br><span class="line">        <span class="comment">//3、读取磁盘上的文件，对应每个文件创建一个文档对象。</span></span><br><span class="line">        File dir = <span class="keyword">new</span> File(<span class="string">"F:\\texts"</span>);</span><br><span class="line">        File[] files = dir.listFiles();</span><br><span class="line">        <span class="keyword">for</span> (File f : files) &#123;</span><br><span class="line">            <span class="comment">//取文件名</span></span><br><span class="line">            String fileName = f.getName();</span><br><span class="line">            <span class="comment">//文件的路径</span></span><br><span class="line">            String filePath = f.getPath();</span><br><span class="line">            <span class="comment">//文件的内容</span></span><br><span class="line">            String fileContent = FileUtils.readFileToString(f, <span class="string">"utf-8"</span>);</span><br><span class="line">            <span class="comment">//文件的大小</span></span><br><span class="line">            <span class="keyword">long</span> fileSize = FileUtils.sizeOf(f);</span><br><span class="line">            <span class="comment">//创建Field</span></span><br><span class="line">            <span class="comment">//参数1：域的名称，参数2：域的内容，参数3：是否存储</span></span><br><span class="line">            Field fieldName = <span class="keyword">new</span> TextField(<span class="string">"name"</span>, fileName, Field.Store.YES);</span><br><span class="line">            Field fieldPath = <span class="keyword">new</span> StoredField(<span class="string">"path"</span>, filePath);</span><br><span class="line">            Field fieldContent = <span class="keyword">new</span> TextField(<span class="string">"content"</span>, fileContent, Field.Store.YES);</span><br><span class="line">            Field fieldSizeValue = <span class="keyword">new</span> LongPoint(<span class="string">"size"</span>, fileSize);</span><br><span class="line">            Field fieldSizeStore = <span class="keyword">new</span> StoredField(<span class="string">"size"</span>, fileSize);</span><br><span class="line">            <span class="comment">//创建文档对象</span></span><br><span class="line">            Document document = <span class="keyword">new</span> Document();</span><br><span class="line">            <span class="comment">//向文档对象中添加域</span></span><br><span class="line">            document.add(fieldName);</span><br><span class="line">            document.add(fieldPath);</span><br><span class="line">            document.add(fieldContent);</span><br><span class="line">            <span class="comment">//document.add(fieldSize);</span></span><br><span class="line">            document.add(fieldSizeValue);</span><br><span class="line">            document.add(fieldSizeStore);</span><br><span class="line">            <span class="comment">//5、把文档对象写入索引库</span></span><br><span class="line">            indexWriter.addDocument(document);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//6、关闭indexwriter对象</span></span><br><span class="line">        indexWriter.close();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<hr>
<h2 id="3、查询索引"><a href="#3、查询索引" class="headerlink" title="3、查询索引"></a><font color="#CD6839">3、查询索引</font></h2><h3 id="3-1、关键词查询"><a href="#3-1、关键词查询" class="headerlink" title="3.1、关键词查询"></a><font color="#FF8247">3.1、关键词查询</font></h3><p>代码实现上上面几乎相同，最基本就是根据<strong>关键词</strong>查询内容，如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">searchIndex</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">//1、创建一个Director对象，指定索引库的位置</span></span><br><span class="line">        Directory directory = FSDirectory.open(<span class="keyword">new</span> File(<span class="string">"F:\\index"</span>).toPath());</span><br><span class="line">        <span class="comment">//2、创建一个IndexReader对象</span></span><br><span class="line">        IndexReader indexReader = DirectoryReader.open(directory);</span><br><span class="line">        <span class="comment">//3、创建一个IndexSearcher对象，构造方法中的参数indexReader对象。</span></span><br><span class="line">        IndexSearcher indexSearcher = <span class="keyword">new</span> IndexSearcher(indexReader);</span><br><span class="line">        <span class="comment">//4、创建一个Query对象，TermQuery</span></span><br><span class="line">        Query query = <span class="keyword">new</span> TermQuery(<span class="keyword">new</span> Term(<span class="string">"name"</span>, <span class="string">"spring"</span>));</span><br><span class="line">        <span class="comment">//5、执行查询，得到一个TopDocs对象</span></span><br><span class="line">        <span class="comment">//参数1：查询对象 参数2：查询结果返回的最大记录数</span></span><br><span class="line">        TopDocs topDocs = indexSearcher.search(query, <span class="number">10</span>);</span><br><span class="line">        <span class="comment">//6、取查询结果的总记录数</span></span><br><span class="line">        System.out.println(<span class="string">"查询总记录数："</span> + topDocs.totalHits);</span><br><span class="line">        <span class="comment">//7、取文档列表</span></span><br><span class="line">        ScoreDoc[] scoreDocs = topDocs.scoreDocs;</span><br><span class="line">        <span class="comment">//8、打印文档中的内容</span></span><br><span class="line">        <span class="keyword">for</span> (ScoreDoc doc :</span><br><span class="line">                scoreDocs) &#123;</span><br><span class="line">            <span class="comment">//取文档id</span></span><br><span class="line">            <span class="keyword">int</span> docId = doc.doc;</span><br><span class="line">            <span class="comment">//根据id取文档对象</span></span><br><span class="line">            Document document = indexSearcher.doc(docId);</span><br><span class="line">            System.out.println(document.get(<span class="string">"name"</span>));</span><br><span class="line">            System.out.println(document.get(<span class="string">"path"</span>));</span><br><span class="line">            System.out.println(document.get(<span class="string">"size"</span>));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//9、关闭IndexReader对象</span></span><br><span class="line">        indexReader.close();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h3 id="3-2、语句查询"><a href="#3-2、语句查询" class="headerlink" title="3.2、语句查询"></a><font color="#FF8247">3.2、语句查询</font></h3><p>当然我们也可以用文本，例如一句话去查询，去查询哪些文件里面包含这句话。那么代码该怎么操作呢？</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">printResult</span><span class="params">(Query query)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    IndexReader indexReader = </span><br><span class="line">        DirectoryReader.open(FSDirectory.open(<span class="keyword">new</span> File(<span class="string">"F:\\index"</span>).toPath()));</span><br><span class="line">    IndexSearcher indexSearcher = <span class="keyword">new</span> IndexSearcher(indexReader);</span><br><span class="line">    <span class="comment">//创建一个QueryPaser对象，两个参数。参数1：默认搜索域，参数2：分析器对象</span></span><br><span class="line">    QueryParser queryParser = <span class="keyword">new</span> QueryParser(<span class="string">"name"</span>, <span class="keyword">new</span> IKAnalyzer());</span><br><span class="line">    <span class="comment">//使用QueryPaser对象创建一个Query对象</span></span><br><span class="line">    Query query = queryParser.parse(<span class="string">"lucene是一个Java开发的全文检索工具包"</span>);</span><br><span class="line">    <span class="comment">//执行查询，查询出10条数据</span></span><br><span class="line">    TopDocs topDocs = indexSearcher.search(query, <span class="number">10</span>);</span><br><span class="line">    System.out.println(<span class="string">"总记录数："</span> + topDocs.totalHits);</span><br><span class="line">    ScoreDoc[] scoreDocs = topDocs.scoreDocs;</span><br><span class="line">    <span class="keyword">for</span> (ScoreDoc doc:scoreDocs)&#123;</span><br><span class="line">        <span class="comment">//取文档id</span></span><br><span class="line">        <span class="keyword">int</span> docId = doc.doc;</span><br><span class="line">        <span class="comment">//根据id取文档对象</span></span><br><span class="line">        Document document = indexSearcher.doc(docId);</span><br><span class="line">        System.out.println(document.get(<span class="string">"name"</span>));</span><br><span class="line">        System.out.println(document.get(<span class="string">"path"</span>));</span><br><span class="line">        System.out.println(document.get(<span class="string">"size"</span>));</span><br><span class="line">    &#125;</span><br><span class="line">    indexReader.close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="3-1、范围查询"><a href="#3-1、范围查询" class="headerlink" title="3.1、范围查询"></a><font color="#FF8247">3.1、范围查询</font></h3><p>我们也可以根据范围进行查询，如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//创建一个Query对象,查询size的范围，最小值01，最大值1001</span></span><br><span class="line">Query query = LongPoint.newRangeQuery(<span class="string">"size"</span>, <span class="number">0l</span>, <span class="number">100l</span>);</span><br><span class="line">printResult(query);</span><br></pre></td></tr></table></figure>
<h2 id="4、维护索引"><a href="#4、维护索引" class="headerlink" title="4、维护索引"></a><font color="#CD6839">4、维护索引</font></h2><h3 id="4-1、添加索引"><a href="#4-1、添加索引" class="headerlink" title="4.1、添加索引"></a><font color="#FF8247">4.1、添加索引</font></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addDocument</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">//创建一个IndexWriter对象，需要使用IKAnalyzer作为分析器</span></span><br><span class="line">        IndexWriter indexWriter =</span><br><span class="line">                <span class="keyword">new</span> IndexWriter(FSDirectory.open(<span class="keyword">new</span> File(<span class="string">"F:\\index"</span>).toPath()),</span><br><span class="line">                <span class="keyword">new</span> IndexWriterConfig(<span class="keyword">new</span> IKAnalyzer()));</span><br><span class="line">        <span class="comment">//创建一个Document对象</span></span><br><span class="line">        Document document = <span class="keyword">new</span> Document();</span><br><span class="line">        <span class="comment">//向document对象中添加域</span></span><br><span class="line">        document.add(<span class="keyword">new</span> TextField(<span class="string">"name"</span>, <span class="string">"新添加的文件"</span>, Field.Store.YES));</span><br><span class="line">        document.add(<span class="keyword">new</span> TextField(<span class="string">"content"</span>, <span class="string">"新添加的文件内容"</span>, Field.Store.NO));</span><br><span class="line">        document.add(<span class="keyword">new</span> StoredField(<span class="string">"path"</span>, <span class="string">"新添加的文件路径"</span>));</span><br><span class="line">        <span class="comment">// 把文档写入索引库</span></span><br><span class="line">        indexWriter.addDocument(document);</span><br><span class="line">        <span class="comment">//关闭索引库</span></span><br><span class="line">        indexWriter.close();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h3 id="4-2、删除索引"><a href="#4-2、删除索引" class="headerlink" title="4.2、删除索引"></a><font color="#FF8247">4.2、删除索引</font></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">deleteAllDocument</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">//删除全部文档</span></span><br><span class="line">    indexWriter.deleteAll();</span><br><span class="line">    <span class="comment">//关闭索引库</span></span><br><span class="line">    indexWriter.close();</span><br><span class="line"> &#125;</span><br><span class="line"><span class="comment">//根据条件删除索引</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">deleteDocumentByQuery</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    indexWriter.deleteDocuments(<span class="keyword">new</span> Term(<span class="string">"name"</span>, <span class="string">"apache"</span>));</span><br><span class="line">    indexWriter.close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="4-3、更新索引"><a href="#4-3、更新索引" class="headerlink" title="4.3、更新索引"></a><font color="#FF8247">4.3、更新索引</font></h3><p>原理就是先删除后添加。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">updateDocument</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">//创建一个新的文档对象</span></span><br><span class="line">        Document document = <span class="keyword">new</span> Document();</span><br><span class="line">        <span class="comment">//向文档对象中添加域</span></span><br><span class="line">        document.add(<span class="keyword">new</span> TextField(<span class="string">"name"</span>, <span class="string">"更新之后的文档"</span>, Field.Store.YES));</span><br><span class="line">        document.add(<span class="keyword">new</span> TextField(<span class="string">"name1"</span>, <span class="string">"更新之后的文档2"</span>, Field.Store.YES));</span><br><span class="line">        document.add(<span class="keyword">new</span> TextField(<span class="string">"name2"</span>, <span class="string">"更新之后的文档3"</span>, Field.Store.YES));</span><br><span class="line">        <span class="comment">//更新操作,要删除的对象</span></span><br><span class="line">        indexWriter.updateDocument(<span class="keyword">new</span> Term(<span class="string">"name"</span>, <span class="string">"spring"</span>), document);</span><br><span class="line">        <span class="comment">//关闭索引库</span></span><br><span class="line">        indexWriter.close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<p>是不是感觉这玩意挺牛的，但是最后不得不说一句，在我们的日常开发中，我们不会选择这个的。这只是让大家了解一下原理。</p>

    </div>
    <p class="post-meta">
        <span class="post-cat">分类：
            <a class="cat-link" href="/blog/categories/Lucene/">Lucene</a>
        </span>
        <span class="post-tags">
            标签：
            
    
        <a href="/blog/tags/Java/" title="Java">Java</a> / 
    
        <a href="/blog/tags/Lucene/" title="Lucene">Lucene</a>
    

        </span>
    </p>
</article>
<!-- 分享按钮 -->

  <div class="article-share clearfix text-center">
    <div class="share-area">
      <span class="share-txt">分享到：</span>
      <a href="javascript: window.open('http://service.weibo.com/share/share.php?url=' + encodeURIComponent(location.href) + '&title=' + document.title + '&language=zh_cn');" class="share-icon weibo"></a>
      <a href="javascript: alert('请复制链接到微信并发送');" class="share-icon wechat"></a>
      <a href="javascript: window.open('http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=' + encodeURIComponent(location.href) + '&title=' + document.title);" class="share-icon qqzone"></a>
      <a href="javascript: window.open('http://connect.qq.com/widget/shareqq/index.html?url=' + encodeURIComponent(location.href) + '&desc=Jelon个人博客&title=' + document.title + '&callback=' + encodeURIComponent(location.href));" class="share-icon qq"></a>
      <a href="javascript: window.open('http://shuo.douban.com/!service/share?href=' + encodeURIComponent(location.href) + '&name=' + document.title + '&text=' + document.title);" class="share-icon douban"></a>
    </div>
  </div>


<!-- 上一篇/下一篇 -->

<div class="article-nav clearfix">
    
    <span class="prev fl">
        上一篇<br>
        <a href="/blog/2019/05/20/Vue/2-vue实现文字滚动效果/">
            
                vue实现文字滚动效果
            
        </a>
    </span>
    

    
    <span class="next fr">
        下一篇<br>
        <a href="/blog/2019/05/15/2019-05-15-iOS10、Chrome、微信7.0无法定位/">
            
                iOS10、Chrome、微信7.0无法定位
            
        </a>
    </span>
    
</div>

<!-- 文章评论 -->

  <script src="/blog/js/comment.js"></script>
  <div id="comments" class="comment">
    <!--
    <div class="sign-bar">
      GitHub 已登录!
      <span class="sign-link">登出</span>
    </div>
    <section class="box">
      <div class="com-avatar"><img src="/blog/logo.png" alt="avatar"></div>
      <div class="com-text">
        <div class="main">
          <textarea class="text-area-edited show" placeholder="欢迎评论！"></textarea>
          <div class="text-area-preview"></div>
        </div>
        <div class="switch">
          <div class="switch-item on">编辑</div>
          <div class="switch-item">预览</div>
        </div>
        <div class="button">提交</div>
      </div>
    </section>
    <section class="tips">注：评论支持 markdown 语法！</section>
    <section class="list-wrap">
      <ul class="list">
        <li>
          <div class="user-avatar">
            <a href="/">
              <img src="/img/jelon.jpg" alt="user-avatar">
            </a>
          </div>
          <div class="user-comment">
            <div class="user-comment-header">
              <span class="post-name">张德龙</span>
              <span class="post-time">2017年12月12日</span>
              <span class="like liked">已赞</span>
              <span class="like-num">2</span>
            </div>
            <div class="user-comment-body">333333</div>
          </div>
        </li>
        <li>
          <div class="user-avatar">
            <a href="/">
              <img src="/img/jelon.jpg" alt="user-avatar">
            </a>
          </div>
          <div class="user-comment">
            <div class="user-comment-header">
              <span class="post-name">刘德华</span>
              <span class="post-time">2017年12月12日</span>
              <span class="like">点赞</span>
              <span class="like-num">2</span>
            </div>
            <div class="user-comment-body">vvvvv</div>
          </div>
        </li>
      </ul>
      <div class="page-nav">
        <a href="javascript: void(0);" class="item">1</a>
        <a href="javascript: void(0);" class="item">2</a>
        <a href="javascript: void(0);" class="item current">3</a>
      </div>
    </section>
    -->
  </div>
  <script>
  JELON.Comment({
    container: 'comments',
    label: 'Lucene/2019-05-12-Lucene快速入门案例' || '2019/05/15/Lucene/2019-05-12-Lucene快速入门案例/',
    owner: 'fxiaoyu97',
    repo: 'blog_comment',
    clientId: 'fxiaoyu97',
    clientSecret: 'Fsy1179006580@'
  });
  </script>


            </div>

        </section>
        <!-- 侧栏部分 -->
<aside class="sidebar">
    <section class="widget">
        <h3 class="widget-hd"><strong>文章分类</strong></h3>
        <!-- 文章分类 -->
<ul class="widget-bd">
    
    <li>
        <a href="/blog/categories/IDEA/">IDEA</a>
        <span class="badge">(1)</span>
    </li>
    
    <li>
        <a href="/blog/categories/Nginx/">Nginx</a>
        <span class="badge">(1)</span>
    </li>
    
    <li>
        <a href="/blog/categories/地图/">地图</a>
        <span class="badge">(1)</span>
    </li>
    
    <li>
        <a href="/blog/categories/Java/">Java</a>
        <span class="badge">(6)</span>
    </li>
    
    <li>
        <a href="/blog/categories/Maven/">Maven</a>
        <span class="badge">(2)</span>
    </li>
    
    <li>
        <a href="/blog/categories/web前端/">web前端</a>
        <span class="badge">(2)</span>
    </li>
    
    <li>
        <a href="/blog/categories/Vue/">Vue</a>
        <span class="badge">(31)</span>
    </li>
    
    <li>
        <a href="/blog/categories/Lucene/">Lucene</a>
        <span class="badge">(1)</span>
    </li>
    
    <li>
        <a href="/blog/categories/SpringBoot/">SpringBoot</a>
        <span class="badge">(10)</span>
    </li>
    
    <li>
        <a href="/blog/categories/Exception/">Exception</a>
        <span class="badge">(1)</span>
    </li>
    
    <li>
        <a href="/blog/categories/MySQL/">MySQL</a>
        <span class="badge">(2)</span>
    </li>
    
    <li>
        <a href="/blog/categories/Spring/">Spring</a>
        <span class="badge">(1)</span>
    </li>
    
</ul>
    </section>

    
    <section class="widget">
        <h3 class="widget-hd"><strong>热门标签</strong></h3>
        <!-- 文章标签 -->
<div class="widget-bd tag-wrap">
  
    <a class="tag-item" href="/blog/tags/IDEA/" title="IDEA">IDEA (1)</a>
  
    <a class="tag-item" href="/blog/tags/快捷键/" title="快捷键">快捷键 (1)</a>
  
    <a class="tag-item" href="/blog/tags/Nginx/" title="Nginx">Nginx (1)</a>
  
    <a class="tag-item" href="/blog/tags/地图/" title="地图">地图 (1)</a>
  
    <a class="tag-item" href="/blog/tags/log4j/" title="log4j">log4j (1)</a>
  
    <a class="tag-item" href="/blog/tags/正则/" title="正则">正则 (1)</a>
  
    <a class="tag-item" href="/blog/tags/JFrame/" title="JFrame">JFrame (1)</a>
  
    <a class="tag-item" href="/blog/tags/爬虫/" title="爬虫">爬虫 (2)</a>
  
    <a class="tag-item" href="/blog/tags/Java/" title="Java">Java (6)</a>
  
    <a class="tag-item" href="/blog/tags/字符串/" title="字符串">字符串 (1)</a>
  
    <a class="tag-item" href="/blog/tags/Maven/" title="Maven">Maven (2)</a>
  
    <a class="tag-item" href="/blog/tags/JavaScript/" title="JavaScript">JavaScript (1)</a>
  
    <a class="tag-item" href="/blog/tags/Vue/" title="Vue">Vue (31)</a>
  
    <a class="tag-item" href="/blog/tags/WebMagic/" title="WebMagic">WebMagic (1)</a>
  
    <a class="tag-item" href="/blog/tags/web前端/" title="web前端">web前端 (3)</a>
  
    <a class="tag-item" href="/blog/tags/HTML/" title="HTML">HTML (1)</a>
  
    <a class="tag-item" href="/blog/tags/webpack/" title="webpack">webpack (12)</a>
  
    <a class="tag-item" href="/blog/tags/Lucene/" title="Lucene">Lucene (1)</a>
  
    <a class="tag-item" href="/blog/tags/SpringBoot/" title="SpringBoot">SpringBoot (9)</a>
  
    <a class="tag-item" href="/blog/tags/注解/" title="注解">注解 (2)</a>
  
    <a class="tag-item" href="/blog/tags/yml/" title="yml">yml (2)</a>
  
    <a class="tag-item" href="/blog/tags/Exception/" title="Exception">Exception (1)</a>
  
    <a class="tag-item" href="/blog/tags/Mysql/" title="Mysql">Mysql (1)</a>
  
    <a class="tag-item" href="/blog/tags/MySQL/" title="MySQL">MySQL (2)</a>
  
    <a class="tag-item" href="/blog/tags/Spring/" title="Spring">Spring (1)</a>
  
    <a class="tag-item" href="/blog/tags/Mybatis/" title="Mybatis">Mybatis (1)</a>
  
</div>
    </section>
    

    

    
</aside>
<!-- / 侧栏部分 -->
    </div>

    <!-- 博客底部 -->
    <footer class="footer">
    &copy;
    
        2016-2019
    

    <a href="/blog/">Todou Loves You</a>
</footer>
<div class="back-to-top" id="JELON__backToTop" title="返回顶部">返回顶部</div>

    <!--博客js脚本 -->
    <!-- 这里放网站js脚本 -->
<script src="/blog/js/main.js"></script>
</body>
</html>